import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class TCPClient {
    private String serverIp;
    private int port;
    private SocketChannel socketChannel;

    public TCPClient(String serverIp, int port) {
        this.serverIp = serverIp;
        this.port = port;
    }
    public void start() throws IOException {
        try {
            this.socketChannel = SocketChannel.open();
            if (serverIp == null) {
                socketChannel.connect(new InetSocketAddress(port));
            }
            else {
                socketChannel.connect(new InetSocketAddress(Inet4Address.getByName(serverIp), port));
            }
//            System.out.println("已发起服务器连接，并进入后续流程～");
//            System.out.println("服务器信息：" + socketChannel.getRemoteAddress().toString());
            System.out.println("客户端信息：" + socketChannel.getLocalAddress().toString());
        } catch (IOException e) {
            System.out.println("连接异常");
            CloseUtils.close(socketChannel);
            throw e;
        }
    }
    public void write(String message) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(message.getBytes().length);
        byteBuffer.put(message.getBytes());
        byteBuffer.flip();
        this.socketChannel.write(byteBuffer);
    }
    public void Close(){
        if (socketChannel.isOpen()) {
            try {
                this.socketChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
